package com.doctor.fss.controller;

import com.doctor.fss.model.TicketResp;
import com.doctor.fss.model.UserResp;
import com.doctor.fss.util.ExceptionUtil;
import com.doctor.fss.util.OkHttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huawei.welink.api.message.MessagesV3SendRequest;
import com.huawei.welink.api.message.MessagesV3SendResponse;
import com.huawei.welink.common.DefaultWeLinkClient;
import com.huawei.welink.common.exception.ApiException;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class FreeloginController {

    private static final Logger logger = LoggerFactory.getLogger(FreeloginController.class);
    public static final MediaType mediaType = MediaType.parse("application/json");

    @Value("${ticket.url}")
    private String ticketUrl;

    @Value("${user.url}")
    private String userUrl;

    @Value("${client.id}")
    private String clientId;

    @Value("${client.secret}")
    private String clientSecret;

    /**
     * 免登
     * H5后台得到WeLink接口返回的user_id后与H5轻应用后台系统用户进行匹配进行单点登录，为用户建立登录态如session或者cookie，避免每次打开都再次走免登流程。
     * @param req
     * @return
     */
    @RequestMapping(value = "/freelogin", method = RequestMethod.GET)
    public String helloCloudLinkUser(HttpServletRequest req) {
        //Step1：获取免登code
        // 免登code可以通过url参数从前端传过来
        // 测试阶段可以通过WeLink扫码复制免登授权码使用https://open-doc.welink.huaweicloud.com/docs/devapi/wecode/jsapi/getAuthCode.html?type=internal
        String code = req.getParameter("code");

        //Step2:获取access token
        //根据client_id,client_secret和已经获取的免登code等参数获取access_token信息
        TicketResp ticketResp  ;
        String accessToken="";
        //获取access token相关参数列表
        String typeParamValue = "u";
        String clientIdParamValue =clientId ;
        String clientSecretParamValue = clientSecret;
        if (clientId == null || clientId.equals("")) {
            System.out.println("请根据README.md文档配置client_id和client_secret");
            System.exit(1);
        }
        String codeValue =code;
        Map<String, String> ticketBodyParams = new HashMap<>();
        ticketBodyParams.put("client_id", clientIdParamValue);
        ticketBodyParams.put("client_secret", clientSecretParamValue);
        //转换相关参数列表为Json格式
        String ticketBody = JSONObject.toJSONString(ticketBodyParams);
        try {
            //发送post请求并获取access token相关信息
            String ticketResult = OkHttpUtil.post(ticketUrl, ticketBody, mediaType);
            ticketResp = JSON.parseObject(ticketResult, TicketResp.class);
            // 请务必根据接口过期时间缓存AccessToken，避免重复获取
            accessToken = ticketResp!=null?ticketResp.getAccess_token():null;
        } catch (Exception e) {
            e.printStackTrace();
            return ExceptionUtil.getExceptionInfo(e);
        }
        //Step3:获取免登用户的userId信息
        //通过access token获取免登用户的userId信息
        Map<String, String> userHeaderParams = new HashMap<>();
        UserResp userResp;
        userHeaderParams.put("x-wlk-Authorization", accessToken);
        Map<String, String> urlParams = new HashMap<>();
        urlParams.put("code", codeValue);
        try{
            //携带access token发送get请求并获取免登用户的userId信息
            String userResult = OkHttpUtil.get(userUrl, userHeaderParams, urlParams);
            System.out.println("userinfo response: " + userResult);
            System.out.println("accessToken: " + accessToken);
            userResp = JSON.parseObject(userResult, UserResp.class);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return ExceptionUtil.getExceptionInfo(e);
        }

        return  userResp.toString();
    }
    public static void main(String[] args){
        /**
         * 公众号消息接口
         * 该接口用于企业应用中需要消息通知的场景。通过本接口，应用可以将信息推送给WeLink端用户。
         */
        //send();

    }

    /**
     * 公众号消息接口
     * 该接口用于企业应用中需要消息通知的场景。通过本接口，应用可以将信息推送给WeLink端用户。
     */
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public String send() {
        try {
            DefaultWeLinkClient client = new DefaultWeLinkClient("https://open.welink.huaweicloud.com/api/messages/v3/send");
            MessagesV3SendRequest req = new MessagesV3SendRequest();
            req.setAccessToken(getAccessToken());
            List<String> reqToUserListList = new ArrayList<>();
            reqToUserListList.add("[\"huangxinhua@jiefang\"]");
            req.setToUserList(reqToUserListList);
            req.setMsgRange("0");
            req.setMsgTitle("{\"EN\": \"hello world\", \"CN\": \"你好\"}");
            req.setMsgContent("{\"CN\": \"欢迎使用\", \"EN\":\"Welcome\"}");
            req.setUrlType("html");
            req.setUrlPath("h5://demo.com");
            req.setMsgOwner("ss");
            MessagesV3SendResponse rsp = client.execute(req);
            System.out.println(rsp.getBody());
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
    }
    public String getAccessToken(){
        //根据client_id,client_secret和已经获取的免登code等参数获取access_token信息
        TicketResp ticketResp  ;
        String clientIdParamValue =clientId ;
        String clientSecretParamValue = clientSecret;
        if (clientId == null || clientId.equals("")) {
            System.out.println("请根据README.md文档配置client_id和client_secret");
            System.exit(1);
        }
        Map<String, String> ticketBodyParams = new HashMap<>();
        ticketBodyParams.put("client_id", clientIdParamValue);
        ticketBodyParams.put("client_secret", clientSecretParamValue);
        //转换相关参数列表为Json格式
        String ticketBody = JSONObject.toJSONString(ticketBodyParams);
        //发送post请求并获取access token相关信息
        String ticketResult = null;
        try {
            ticketResult = OkHttpUtil.post(ticketUrl, ticketBody, mediaType);
            ticketResp = JSON.parseObject(ticketResult, TicketResp.class);
            // 请务必根据接口过期时间缓存AccessToken，避免重复获取
            return ticketResp!=null?ticketResp.getAccess_token():null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
